package com.ltcode.log.starter.utils;


import com.ltcode.log.starter.entity.ThreadLocalEntity;

public class LogContextUtil {
    // 在新线程中设置父线程的日志上下文
    public static void setParentContext(ThreadLocalEntity parentContext) {
        if (parentContext != null) {
            ThreadLocalEntity copy = ThreadLocalEntity.createCopy(parentContext);
            LogUtils.setThreadLocalEntity(copy);
        }
    }

    // 获取当前线程的日志上下文
    public static ThreadLocalEntity getCurrentContext() {
        return LogUtils.getThreadLocalEntity();
    }

    // 在新线程中执行任务并自动传递日志上下文
    public static void runWithLogContext(Runnable task) {
        ThreadLocalEntity context = LogUtils.getThreadLocalEntity();
        Thread thread = new Thread(() -> {
            try {
                setParentContext(context);
                task.run();
            } finally {
                clearCurrentContext();
            }
        });
        thread.start();
    }

    // 提交任务到线程池并自动传递日志上下文
    public static <T> java.util.concurrent.Future<T> submitWithLogContext(java.util.concurrent.Callable<T> task) {
        ThreadLocalEntity context = LogUtils.getThreadLocalEntity();
        return java.util.concurrent.Executors.newSingleThreadExecutor().submit(() -> {
            try {
                setParentContext(context);
                return task.call();
            } finally {
                clearCurrentContext();
            }
        });
    }

    // 清理当前线程的日志上下文
    public static void clearCurrentContext() {
        if (LogUtils.getThreadLocalEntity() != null && LogUtils.getThreadLocalEntity().getDataEntityStack() != null) {
            LogUtils.getThreadLocalEntity().getDataEntityStack().clear();
        }
        LogUtils.getThreadLocalEntity().getDataEntityStack().clear();
        LogUtils.setThreadLocalEntity(null);
    }
}